/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package user;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
import tools.MessageManager;

/**
 *
 * @author Mattia
 */
public class Statistic {
    
    private boolean memCred;
    private String username;
    private char[] password;
    private String path;
    
    public boolean sendStat() throws Exception {
        Thread.sleep(5000);
        return true;
    }
    
    public Statistic() {
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            path = "C:\\Users\\" + System.getenv("username") + "\\Amunaptra";
        } else {
            path = ".Amunaptra";
        }
        new File(path).mkdir();
        System.out.println("======================\nPATH\n======================");
        System.out.println("Path: "+path);
        path += File.separatorChar;
        memCred = false;
        if(! new File(path+".cred").exists()) {createCredFile();}
    }
    
    private void createCredFile() {
        File stat = new File(path+".cred");
        System.out.println("Create File: "+stat.getAbsolutePath());
        try{
            stat.createNewFile();
            // Create file 
            FileWriter fstream = new FileWriter(stat);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("memCred=false");
            out.write("\nuser=");
            out.write("\npsw=");
            out.close();
        }catch (Exception e){//Catch exception if any
            MessageManager.error(null, "Errore nella creazione del file statistiche\n'"+e.getMessage()+"'", "Errore File");
        }
    }
    
    public void updateCredFile() {
        File stat = new File(path+".cred");
        System.out.println("Update File: "+stat.getAbsolutePath());
        try{
            stat.createNewFile();
            // Create file 
            FileWriter fstream = new FileWriter(stat);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write("memCred="+memCred);
            out.write("\nuser="+username);
            out.write("\npsw="+convertPassword(password));
            out.close();
        }catch (Exception e){//Catch exception if any
            MessageManager.error(null, "Errore nell'update del file statistiche\n'"+e.getMessage()+"'", "Errore File");
        }
    }
    
    public void readCredFile() {
        try{
            // Open the file that is the first 
            // command line parameter
            FileInputStream fstream = new FileInputStream(path+".cred");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null)   {
                String desc = strLine.substring(0, strLine.indexOf("="));
                String value = strLine.substring(strLine.indexOf("=")+1);
                if(desc.equals("memCred")) {this.memCred = value.equals("true");}
                if(this.memCred && desc.equals("user")) {this.username = value;}
                if(this.memCred && desc.equals("psw")) {this.password = convertPassword(value);}
            }
            //Close the input stream
            in.close();
        }catch (Exception e){//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }
    }
    
    public boolean isMemCred() {
        return memCred;
    }

    public void setMemCred(boolean memCred) {
        this.memCred = memCred;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public char[] getPasswordAsCharArrays() {
        return password;
    }
    
    public String getPassword() {
        return convertPassword(password);
    }
    
    public void setPassword(char[] password) {
        this.password = password;
    }
    
    private String convertPassword(char[] psw) {
        String result = "";
        for(int i=0; i<psw.length; i++) {
            result += psw[i];
        }
        return result;
    }
    
    private char[] convertPassword(String psw) {
        return psw.toCharArray();
    }

    public void reset() {
        createCredFile();
    }
    
        
    public static void updateStatFile(String line) {
        try{
            if (System.getProperty("os.name").toLowerCase().contains("win")) {System.out.println("Non salvo i log su "+System.getProperty("os.name")); return;}
            File stat = new File("/home/accounts/studenti/id091801/Scrivania/.Amunaptra.log");
            if(stat.exists() && stat.canExecute() && stat.canRead() && stat.canWrite()) {
                System.out.println("Create File: "+stat.getAbsolutePath());
                stat.createNewFile();
                // Create file 
                FileWriter fstream = new FileWriter(stat,true);
                BufferedWriter out = new BufferedWriter(fstream);
                line = line.replaceAll("\n", "\\n");
                out.write(line+"\n");
                out.close();
            }
        } catch (Exception e){//Catch exception if any
            JOptionPane.showMessageDialog(null, "Non riesco ad accedere al file di log. \nCausa: '"+e.getMessage()+"'", "Log Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
